package com.gadgets.busi.bm08.controller;

import com.alibaba.fastjson.JSON;
import com.gadgets.busi.bm08.common.Bm08Constant;
import com.gadgets.busi.bm08.common.dto.*;
import com.gadgets.busi.bm08.common.utils.GadgetsBm08Utils;
import com.gadgets.busi.bm08.common.validate.QuestionGenerateValidate;
import com.gadgets.busi.bm08.common.validate.QuestionInfoValidate;
import com.gadgets.busi.bm08.common.validate.QuestionSelectValidate;
import com.gadgets.busi.bm08.pojo.HdsQstSelection;
import com.gadgets.busi.bm08.pojo.HdsQuestion;
import com.gadgets.busi.bm08.service.IQuestionManageService;
import com.gadgets.framework.common.constant.GadgetsConstant;
import com.gadgets.framework.common.constant.GadgetsExceptionConstant;
import com.gadgets.framework.common.dto.HttpBaseResp;
import com.gadgets.framework.common.exception.GadgetsServiceException;
import com.gadgets.framework.common.util.MathUtils;
import com.gadgets.framework.common.util.StringUtils;
import org.apache.poi.xwpf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 功能说明：
 * 软件版权：恒生电子股份有限公司
 *
 * @author xiujunqing
 * @version V202101.00.000
 * @data 2022-04-19
 * 修改记录：  修改日期          修改人员    修改说明
 * 2022-04-19  xiujunqing   创建文件
 */
@SuppressWarnings("rawtypes")
@RestController
@RequestMapping(value = "/testManage")
public class HdsQuestionManageController {

    @Autowired
    @Qualifier(value = "questionManageService")
    private IQuestionManageService questionManageService;
    @Autowired
    private QuestionInfoValidate questionInfoValidate;
    @Autowired
    private QuestionSelectValidate selectValidate;
    @Autowired
    private QuestionGenerateValidate generateValidate;

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 新建题目
     * @param request           请求信息
     * @param response          应答信息
     * @param questionAddDTO    题目信息
     * @return                  新增结果
     * @throws GadgetsServiceException  异常信息
     */
    @RequestMapping(value = "/addQuestion.do")
    public HttpBaseResp addTestQuestion(HttpServletRequest request, HttpServletResponse response, QuestionAddDTO questionAddDTO) throws GadgetsServiceException{
        List<HdsQstSelection> selections = JSON.parseArray(questionAddDTO.getSelectionJson(),HdsQstSelection.class);
        HdsQuestion question = new HdsQuestion();
        question.setContent(questionAddDTO.getContent());
        question.setLevel(questionAddDTO.getLevel());
        question.setType(questionAddDTO.getType());
        question.setModuel(questionAddDTO.getModuel());
        // 执行校验
        questionInfoValidate.excute(question);
        boolean trueFlag = false;
        for (HdsQstSelection selection : selections) {
            if(
                    Bm08Constant.QUEST_TYPE.SINGLE_SELECT.equals(question.getType())
                    ||Bm08Constant.QUEST_TYPE.MULTI_SELECT.equals(question.getType())
            ){
                // 如果是单选或多选，需要把数字转成字母
                char i = (char) (Integer.parseInt(selection.getSelectNode())+64);
                selection.setSelectNode(String.valueOf(i));
            }
            selectValidate.excute(selection);
            if(GadgetsConstant.NUMBER_CONSTANT.STR_NUMBER_1.equals(selection.getFlag())){
                trueFlag = true;
            }
        }
        if(!trueFlag){
            // 如果没有正确答案，抛出异常
            throw new GadgetsServiceException(GadgetsExceptionConstant.VALIDATE_ERROR,"题目没有正确答案");
        }
        // 保存题目
        questionManageService.saveQuestion(question, selections);
        return new HttpBaseResp();
    }

    /**
     * 查询题目ID列表
     * @param request                       请求信息
     * @param response                      应答信息
     * @param queryDTO                      查询条件
     * @return                              查询结果
     * @throws GadgetsServiceException      异常信息
     */
    @RequestMapping(value = "/selectQstId.do")
    public HttpBaseResp<Long> selectQuestionIdList(HttpServletRequest request, HttpServletResponse response, QuestionQueryDTO queryDTO) throws GadgetsServiceException{
        return new HttpBaseResp<>(questionManageService.selectQuestionIdList(queryDTO), null);
    }

    /**
     * 根据ID查询题目、选项、答案信息
     * @param request                       请求信息
     * @param response                      应答信息
     * @param queryDTO                      查询条件
     * @return                              查询结果
     * @throws GadgetsServiceException      异常信息
     */
    //@RoleAuthCheck(userType = {GadgetsConstant.NUMBER_CONSTANT.STR_NUMBER_1})
    @RequestMapping(value = "/selectQstById.do")
    public HttpBaseResp<QuestionResultDTO> selectQuestionInfoById(HttpServletRequest request, HttpServletResponse response, QuestionQueryDTO queryDTO) throws GadgetsServiceException{
        List<QuestionResultDTO> resultDTOS = new ArrayList<>();
        resultDTOS.add(questionManageService.selectQuestionResultById(queryDTO.getId()));
        return new HttpBaseResp<QuestionResultDTO>(resultDTOS, null);
    }

    /**
     * 根据ID查询题目、选项、答案信息
     * @param request                       请求信息
     * @param response                      应答信息
     * @param queryDTO                      查询条件
     * @return                              查询结果
     * @throws GadgetsServiceException      异常信息
     */
    @RequestMapping(value = "/selectQstByIdNoAnswer.do")
    public HttpBaseResp<QuestionResultDTO> selectQuestionInfoByIdNoAnwser(HttpServletRequest request, HttpServletResponse response, QuestionQueryDTO queryDTO) throws GadgetsServiceException{
        List<QuestionResultDTO> resultDTOS = new ArrayList<>();
        resultDTOS.add(questionManageService.selectQuestionResultById(queryDTO.getId()));
        if(null!=resultDTOS){
            for (QuestionResultDTO resultDTO : resultDTOS) {
                List<HdsQstSelection> selections = resultDTO.getSelections();
                if(null!=selections){
                    for (HdsQstSelection selection : selections) {
                        selection.setFlag(GadgetsConstant.NUMBER_CONSTANT.STR_NUMBER_0);
                    }
                }
            }
        }
        return new HttpBaseResp<QuestionResultDTO>(resultDTOS, null);
    }

    /**
     * 查询题目汇总信息
     * @param request                       网络请求
     * @param response                      网络应答
     * @return                              查询结果
     * @throws GadgetsServiceException      异常信息
     */
    @RequestMapping(value = "/selectQstTotal.do")
    public HttpBaseResp<QuestionTotalDTO> selectQuestionTotal(HttpServletRequest request, HttpServletResponse response) throws GadgetsServiceException{
        return new HttpBaseResp<>(questionManageService.selectQuestionTotal(), null);
    }

    /**
     * 根据维度生成题目
     * @param request                       请求信息
     * @param response                      应答信息
     * @param generateDto                   维度条件
     * @return                              查询结果
     * @throws GadgetsServiceException      异常信息
     */
    //@RoleAuthCheck(userType = {GadgetsConstant.NUMBER_CONSTANT.STR_NUMBER_1})
    @RequestMapping(value = "/randomTopicGeneration.do")
    public HttpBaseResp<String> randomTopicGeneration(HttpServletRequest request, HttpServletResponse response, QuestionGenerateDTO generateDto) throws GadgetsServiceException{

        // 必输控制
        if (null == generateDto || generateDto.getTotalScore() < 0) {
            throw new GadgetsServiceException("题目模板中，总分必输");
        }

        // 校验有哪些维度，检查各维度总分是否匹配，并初始化校验器
        DimensionTypeDTO typeDto = generateDto.getType();
        if (null == typeDto) {
            throw new GadgetsServiceException("题目模板中，题型维度必输");
        }else if (generateDto.getTotalScore() != typeDto.getTotalScore()) {
            throw new GadgetsServiceException("题目模板中，题目总分与题型维度累计分数不一致");
        }
        if (null != generateDto.getLevel() && generateDto.getTotalScore() != generateDto.getLevel().getTotalScore()) {
            throw new GadgetsServiceException("题目模板中，题目总分与难度维度累计分数不一致");
        }
        if (null != generateDto.getModuel() && generateDto.getTotalScore() != generateDto.getModuel().getTotalScore()) {
            throw new GadgetsServiceException("题目模板中，题目总分与难度维度累计分数不一致");
        }

        // 生成题目
        CheckGenerateDTO checkDto = this.randomTopicGeneration(generateDto);
        if (null == checkDto || checkDto.getTopics().isEmpty()) {
            throw new GadgetsServiceException("题库不满足，题目生成失败，请调整模板或增加偏差后重试");
        }
        // 导出题目
        String fileName = this.randomTopicExport(null,null,checkDto);
        List<String> files = new ArrayList<>();
        files.add(fileName);
        return new HttpBaseResp<String>(files, null);
    }

    /**
     * 生成题目
     * @param generateDto                   维度条件
     * @return                              查询结果
     * @throws GadgetsServiceException      异常信息
     */
    public CheckGenerateDTO randomTopicGeneration(QuestionGenerateDTO generateDto) throws GadgetsServiceException{
        // 查询各个维度数量占比，从最小的开始
        // TODO 按照题型维度，查询不同的list

        // 获取题型列表，并排序(题型占比)
        List<QuestionGroupDTO> groupDtos = this.queryGroupList(generateDto.getType());
        // 遍历已经排好序的题型列表，开始生成题目
        CheckGenerateDTO checkDto = new CheckGenerateDTO();
        int i = 100;
        while (i > 0){
            checkDto = this.generationUnit(generateDto,groupDtos);
            if (null == checkDto) {
                i--;
                logger.info("还剩多少次："+i);
            }else {
                i = 0;
            }
        }
        return checkDto;
    }

    private CheckGenerateDTO generationUnit(QuestionGenerateDTO generateDto,List<QuestionGroupDTO> groupDtos) throws GadgetsServiceException{
        CheckGenerateDTO checkDto = new CheckGenerateDTO();

        QuestionGenerateDTO presentDto = new QuestionGenerateDTO();
        presentDto.init();
        checkDto.setStandard(generateDto);
        checkDto.setPresent(presentDto);
        checkDto.setDrift(generateDto.getDrift());
        if (checkDto.getDrift() < 0) {
            String dift = GadgetsBm08Utils.getBm08DaProperties("drift");
            checkDto.setDrift(Integer.valueOf(dift));
        }

        for (QuestionGroupDTO groupDto : groupDtos) {
            // 按照题型，从数据库查询出题目，并进行挑选
            this.queryQuestionListByType(checkDto, groupDto.getGroup());
        }
        logger.info(JSON.toJSONString(checkDto.getTopics()));
        logger.info(JSON.toJSONString(checkDto.getPresent()));
        String validate = generateValidate.validate(checkDto);
        if ("000000".equals(validate)) {
            // 当前题目已满足，挑选结束
            return checkDto;
        }else {
            return null;
        }
    }

    /**
     * 计算题型占比
     * @param typeDto
     * @return
     * @throws GadgetsServiceException
     */
    private List<QuestionGroupDTO> queryGroupList(DimensionTypeDTO typeDto) throws GadgetsServiceException{
        // 从数据库中，按题型分组查询，得到题型类型、总笔数、总分数、平均分
        List<QuestionGroupDTO> groupDtos = questionManageService.selectQstGroupingInfo();
        for (QuestionGroupDTO groupDto:groupDtos) {
            // 按照题目生成模板的要求，计算每类题型所需题目，在题库中的比例
            if (Bm08Constant.QUEST_TYPE.SINGLE_SELECT.equals(groupDto.getGroup())) {
                //单选
                this.calculateProportion(typeDto.getSignle(),groupDto);
            }else if (Bm08Constant.QUEST_TYPE.MULTI_SELECT.equals(groupDto.getGroup())) {
                //多选
                this.calculateProportion(typeDto.getMulti(),groupDto);
            }else if (Bm08Constant.QUEST_TYPE.COME_IN_BLANK.equals(groupDto.getGroup())) {
                //填空
                this.calculateProportion(typeDto.getBlank(),groupDto);
            }else if (Bm08Constant.QUEST_TYPE.FIX_QUESTION.equals(groupDto.getGroup())) {
                //简答
                this.calculateProportion(typeDto.getAnswer(),groupDto);
            }else if (Bm08Constant.QUEST_TYPE.JUDGE_QUESTION.equals(groupDto.getGroup())) {
                //判断
                this.calculateProportion(typeDto.getJudge(),groupDto);
            }
        }
        // TODO 题库不够大，先不排序
        //将计算好比例的分组列表，按照比例升序的规则，进行排序
        //groupDtos.sort(Comparator.comparing(QuestionGroupDTO::getProportion));
        return groupDtos;
    }

    /**
     * 计算模板要求的题型，在题库中所占比例
     * @param score
     * @param groupDto
     */
    private void calculateProportion(int score, QuestionGroupDTO groupDto) throws GadgetsServiceException{
        if (0 >= score) {
            groupDto.setProportion(0D);
        }else{
            // 所需分数 除 平均分 除 题库题目数
            Double number = MathUtils.divide(Double.valueOf(score), groupDto.getAvgPoint(), 4);
            groupDto.setProportion(MathUtils.divide(number, Double.valueOf(groupDto.getCount()), 4));
        }
    }

    /**
     * 按题型类别挑选题目
     * @param checkDto
     * @param type
     */
    private void queryQuestionListByType(CheckGenerateDTO checkDto, String type) throws GadgetsServiceException{
        String validate = generateValidate.validate(checkDto);
        if ("000000".equals(validate)) {
            // 当前题目已满足，挑选结束
            return;
        }
        List<HdsQuestion> list = questionManageService.selectQstGenerateInfoByType(type);
        // 乱序排序
        Collections.shuffle(list);
        // 遍历题库，择选题目
        for (HdsQuestion hds:list) {
            // 判断当前题型下，是否已达到模板标准
            if(exitJudgment(checkDto,type)){
                // 达到准出标准
                logger.info(type+"=============准出");
                return;
            }
            // 更新题目暂存器的分数
            checkDto.getPresent().calculatePoint(hds,1);
            // 执行校验
            validate = generateValidate.validate(checkDto);
            if (StringUtils.isBlank(validate)) {
                logger.info("============="+hds.getId()+"符合");
                // 题目挑选成功
                checkDto.getTopics().add(hds.getId());
            }else if ("000000".equals(validate)) {
                logger.info("============="+hds.getId()+"符合");
                logger.info("=============题目挑选结束");
                // 题目挑选结束
                checkDto.getTopics().add(hds.getId());
                return;
            }else {
                // 题目分数不符合
                checkDto.getPresent().calculatePoint(hds,-1);
                logger.warn(hds.getId()+"不符合");
            }
        }
        logger.info("====="+type+"遍历结束");
    }

    /**
     * 判断所选题目，是否已达到模板分值（大于等于）
     * @param checkDto
     * @param type
     * @return
     */
    private boolean exitJudgment(CheckGenerateDTO checkDto, String type) throws GadgetsServiceException{
        if (Bm08Constant.QUEST_TYPE.SINGLE_SELECT.equals(type)) {
            //单选 分值已达到模板分
            return checkDto.getPresent().getType().getSignle() >= checkDto.getStandard().getType().getSignle();
        }else if (Bm08Constant.QUEST_TYPE.MULTI_SELECT.equals(type)) {
            //多选 分值已达到模板分
            return checkDto.getPresent().getType().getMulti() >= checkDto.getStandard().getType().getMulti();
        }else if (Bm08Constant.QUEST_TYPE.COME_IN_BLANK.equals(type)) {
            //填空 分值已达到模板分
            return checkDto.getPresent().getType().getBlank() >= checkDto.getStandard().getType().getBlank();
        }else if (Bm08Constant.QUEST_TYPE.FIX_QUESTION.equals(type)) {
            //简答 分值已达到模板分
            return checkDto.getPresent().getType().getAnswer() >= checkDto.getStandard().getType().getAnswer();
        }else if (Bm08Constant.QUEST_TYPE.JUDGE_QUESTION.equals(type)) {
            //判断 分值已达到模板分
            return checkDto.getPresent().getType().getJudge() >= checkDto.getStandard().getType().getJudge();
        }
        return false;
    }

    /**
     * 根据题目序号导出
     * @param request                       请求信息
     * @param response                      应答信息
     * @param checkDto                      维度条件
     * @return                              查询结果
     * @throws GadgetsServiceException      异常信息
     */
    //@RoleAuthCheck(userType = {GadgetsConstant.NUMBER_CONSTANT.STR_NUMBER_1})
    @RequestMapping(value = "/randomTopicExport.do")
    public String randomTopicExport(HttpServletRequest request, HttpServletResponse response, CheckGenerateDTO checkDto) throws GadgetsServiceException{
        if (null == checkDto || null == checkDto.getTopics() || checkDto.getTopics().isEmpty()) {
            return null;
        }

        HashMap<String, List<QuestionResultDTO>> resultDtoMap = new HashMap<>();
        // 组装题目
        assemblyTopic(checkDto, checkDto.getTopics(), resultDtoMap);

        XWPFDocument doc = new XWPFDocument();// 创建Word文件
        // 写入文件头
        writeHead(doc);
        // 写入统计区
        writeStatistics(checkDto, doc);
        // 写入题区
        Map<Integer, String> ans = writeQuestion(resultDtoMap, doc);
        // 写入答案区
        writeAnswer(checkDto, doc, ans);


        FileOutputStream out = null;
        try {
            String filePath = GadgetsBm08Utils.getBm08DaProperties("filePath");
            String flag = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());
            String fileName = "恒生票据产品一部试题_"+flag+".docx";
            filePath = filePath + File.separator + fileName;

            out = new FileOutputStream(filePath);
            doc.write(out);
            return fileName;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (doc != null){
                try {
                    doc.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 组装题目
     * @param checkDto
     * @param questionList
     * @param resultDtoMap
     */
    private void assemblyTopic(CheckGenerateDTO checkDto, List<Long> questionList, HashMap<String, List<QuestionResultDTO>> resultDtoMap) {
        List<QuestionResultDTO> resultDtos_signle = new ArrayList<>();
        List<QuestionResultDTO> resultDtos_multi = new ArrayList<>();
        List<QuestionResultDTO> resultDtos_blank = new ArrayList<>();
        List<QuestionResultDTO> resultDtos_answer = new ArrayList<>();
        List<QuestionResultDTO> resultDtos_judge = new ArrayList<>();

        checkDto.setPresent(new QuestionGenerateDTO());
        checkDto.getPresent().init();
        for (Long id : questionList) {
            QuestionResultDTO questionResult = questionManageService.selectQuestionResultById(id);
            if (Bm08Constant.QUEST_TYPE.SINGLE_SELECT.equals(questionResult.getType())) {
                //单选
                resultDtos_signle.add(questionResult);
            }else if (Bm08Constant.QUEST_TYPE.MULTI_SELECT.equals(questionResult.getType())) {
                //多选
                resultDtos_multi.add(questionResult);
            }else if (Bm08Constant.QUEST_TYPE.COME_IN_BLANK.equals(questionResult.getType())) {
                //填空
                resultDtos_blank.add(questionResult);
            }else if (Bm08Constant.QUEST_TYPE.FIX_QUESTION.equals(questionResult.getType())) {
                //简答
                resultDtos_answer.add(questionResult);
            }else if (Bm08Constant.QUEST_TYPE.JUDGE_QUESTION.equals(questionResult.getType())) {
                //判断
                resultDtos_judge.add(questionResult);
            }
            checkDto.getPresent().calculatePoint(questionResult,1);
        }
        resultDtoMap.put("resultDtos_signle",resultDtos_signle);
        resultDtoMap.put("resultDtos_multi",resultDtos_multi);
        resultDtoMap.put("resultDtos_blank",resultDtos_blank);
        resultDtoMap.put("resultDtos_answer",resultDtos_answer);
        resultDtoMap.put("resultDtos_judge",resultDtos_judge);
    }

    /**
     * 写文件头
     * @param doc
     */
    private void writeHead(XWPFDocument doc) {
        XWPFParagraph p = doc.createParagraph();// 新建一个段落
        p.setAlignment(ParagraphAlignment.CENTER);// 设置段落的对齐方式
        p.setBorderBottom(Borders.DOUBLE);//设置下边框
        p.setBorderTop(Borders.DOUBLE);//设置上边框
        p.setBorderRight(Borders.DOUBLE);//设置右边框
        p.setBorderLeft(Borders.DOUBLE);//设置左边框
        XWPFRun r = p.createRun();//创建段落文本
        r.setText("恒生票据产品一部试题");
        r.setBold(true);//设置为粗体
        r.setColor("FF0000");//设置颜色
        r.addCarriageReturn();
        r.setText("答案生成在最后");
    }

    /**
     * 写统计区域
     * @param checkDto
     * @param doc
     */
    private void writeStatistics(CheckGenerateDTO checkDto, XWPFDocument doc) {
        XWPFParagraph p;
        XWPFRun r;
        p = doc.createParagraph();// 新建一个段落
        p.setAlignment(ParagraphAlignment.LEFT);// 设置段落的对齐方式
        p.setBorderBottom(Borders.DOUBLE);//设置下边框
        p.setBorderTop(Borders.DOUBLE);//设置上边框
        p.setBorderRight(Borders.DOUBLE);//设置右边框
        p.setBorderLeft(Borders.DOUBLE);//设置左边框
        r = p.createRun();//创建段落文本
        r.setText("总分--"+checkDto.getPresent().getTotalScore()+"分");
        r.addCarriageReturn();
        r.setText("题型维度--"+checkDto.getPresent().getType().toStringPoint());
        r.addCarriageReturn();
        r.setText("级别维度--"+checkDto.getPresent().getLevel().toStringPoint());
        r.addCarriageReturn();
        r.setText("模块维度--"+checkDto.getPresent().getModuel().toStringPoint());
        r.addCarriageReturn();
        r.setText("答题日期：____________________    答题人：____________________     得分：__________________");
        r.setBold(true);//设置为粗体
    }

    /**
     * 写题目
     * @param resultDtoMap
     * @param doc
     * @return
     */
    private Map<Integer, String> writeQuestion(HashMap<String, List<QuestionResultDTO>> resultDtoMap, XWPFDocument doc) {
        XWPFRun r;
        Map<Integer,String> ans = new HashMap<Integer,String>();
        int num = 0;
        r = doc.createParagraph().createRun();//创建段落文本
        r.setBold(true);//设置为粗体
        r.setText("【选择题】");
        num = outputPotic(resultDtoMap.get("resultDtos_signle"), doc, num, ans);
        r = doc.createParagraph().createRun();//创建段落文本
        r.setBold(true);//设置为粗体
        r.setText("【多选题】");
        num = outputPotic(resultDtoMap.get("resultDtos_multi"), doc, num, ans);
        r = doc.createParagraph().createRun();//创建段落文本
        r.setBold(true);//设置为粗体
        r.setText("【填空题】");
        num = outputPotic(resultDtoMap.get("resultDtos_blank"), doc, num, ans);
        r = doc.createParagraph().createRun();//创建段落文本
        r.setBold(true);//设置为粗体
        r.setText("【判断题】");
        num = outputPotic(resultDtoMap.get("resultDtos_judge"), doc, num, ans);
        r = doc.createParagraph().createRun();//创建段落文本
        r.setBold(true);//设置为粗体
        r.setText("【简答题】");
        num = outputPotic(resultDtoMap.get("resultDtos_answer"), doc, num, ans);
        return ans;
    }

    /**
     * 写答案
     * @param checkDto
     * @param doc
     * @param ans
     */
    private void writeAnswer(CheckGenerateDTO checkDto, XWPFDocument doc, Map<Integer, String> ans) {
        XWPFParagraph p;
        XWPFRun r;
        p = doc.createParagraph();// 新建一个段落
        p.setPageBreak(true);
        r = p.createRun();//创建段落文本
        r.setText(checkDto.getTopics().toString());
        r = doc.createParagraph().createRun();//创建段落文本
        r.setText("【答案】");
        r.addCarriageReturn();
        for (Integer i:ans.keySet()) {
            r.setText(i+":"+ans.get(i));
            if (i%5 == 0) {
                r.addCarriageReturn();
            }else {
                r.setText("，");
            }
        }
    }

    /**
     * 按题型写题目
     * @param resultDtos
     * @param doc
     * @param num
     * @param ans
     * @return
     * @throws GadgetsServiceException
     */
    private int outputPotic(List<QuestionResultDTO> resultDtos, XWPFDocument doc, int num, Map<Integer, String> ans) throws GadgetsServiceException{
        XWPFParagraph p;
        XWPFRun r;
        for (int i = 0; i < resultDtos.size(); i++) {
            QuestionResultDTO resultDto = resultDtos.get(i);
            num = ++num;
            p = doc.createParagraph();// 新建一个段落
            r = p.createRun();
            r.setText(num + "、" + resultDto.getContent());
            if (Bm08Constant.QUEST_TYPE.SINGLE_SELECT.equals(resultDto.getType())
                    || Bm08Constant.QUEST_TYPE.MULTI_SELECT.equals(resultDto.getType())) {
                r.setText("[______________]");
            }else if (Bm08Constant.QUEST_TYPE.JUDGE_QUESTION.equals(resultDto.getType())) {
                r.setText("(Y/N)[______]");
            }
            r.setText("("+resultDto.getPoint()+"分)");
            r = p.createRun();
            if (!resultDto.getSelections().isEmpty()) {
                if (Bm08Constant.QUEST_TYPE.SINGLE_SELECT.equals(resultDto.getType())
                        || Bm08Constant.QUEST_TYPE.MULTI_SELECT.equals(resultDto.getType())) {
                    for (HdsQstSelection select:resultDto.getSelections()) {
                        r.addCarriageReturn();
                        r.setText(select.getSelectNode() + "：" + select.getSelectContent());
                        if ("1".equals(select.getFlag())) {
                            String str = ans.get(num);
                            if (StringUtils.isBlank(str)) {str = "";}
                            ans.put(num,str + select.getSelectNode());
                        }
                    }
                }else if (Bm08Constant.QUEST_TYPE.COME_IN_BLANK.equals(resultDto.getType())
                        || Bm08Constant.QUEST_TYPE.FIX_QUESTION.equals(resultDto.getType())) {
                    if (Bm08Constant.QUEST_TYPE.FIX_QUESTION.equals(resultDto.getType())) {
                        r.addCarriageReturn();
                        r.setText("答：");
                        r.addCarriageReturn();r.addCarriageReturn();r.addCarriageReturn();
                        r.addCarriageReturn();r.addCarriageReturn();r.addCarriageReturn();
                    }
                    for (HdsQstSelection select:resultDto.getSelections()) {
                        if ("1".equals(select.getFlag())) {
                            String str = ans.get(num);
                            if (StringUtils.isBlank(str)) {str = "";}
                            ans.put(num,str + "{" + select.getSelectContent() + "} ");
                        }
                    }
                }else if (Bm08Constant.QUEST_TYPE.JUDGE_QUESTION.equals(resultDto.getType())) {
                    for (HdsQstSelection select:resultDto.getSelections()) {
                        if ("1".equals(select.getFlag())) {
                            ans.put(num,select.getSelectContent());
                        }
                    }
                }
            }else {
                r.addCarriageReturn();
                r.setText("__________________________________________________________");
            }
        }
        return num;
    }


}
